import { Entity, HeadingPitchRange, Math as cesiumMath } from "cesium";
import { mergeEntity, generate } from "../utils/generator";

export default {
  props: {
    properties: {
      type: Object,
      default: () => {
        return {};
      }
    },
    preConfig: {
      type: Function,
      default: () => {}
    },
    autoZoom: {
      type: Boolean,
      default: false
    },
    zoomOffset: {
      type: HeadingPitchRange | String,
      default: ""
    },
    show: {
      type: Boolean,
      default: true
    },
    currentStatus: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      ready: false
    };
  },
  watch: {
    currentStatus(n) {
      if (this.kmlConfig) {
        this.kmlConfig.then(soure => {
          soure.show = n;
        });
      }
    },
    show(n) {
      if (this.entity) {
        this.entity.show = n;
      }
    },
    properties: {
      handler(n) {
        this.updateEntity(n);
      },
      deep: true
    }
  },
  created() {
    this.viewer = this.$parent.viewer;
    this.eventBus = this.$parent.eventBus;
    this.create();
  },
  beforeDestroy() {
    this.remove();
  },
  methods: {
    updateEntity(properties) {
      if (this.realEntity) {
        mergeEntity(properties, this.realEntity);
      }
    },
    create() {
      const viewer = this.viewer;
      if (!viewer) return;
      const param = {
        show: this.show
      };

      param[this.entityType] = {};
      this.entity = new Entity(param);

      this.entity.$emit = this.$emit.bind(this);
      this.realEntity = this.entity[this.entityType];

      this.updateEntity(this.properties);

      this.preConfig(this.entity);
      viewer.entities.add(this.entity);

      if (this.entityType === "kml") {
        //加载广州地图
        this.loadGzmodel("/fabu-admin/kml/gz.kml");
      }
    },
    zoomTo() {
      const viewer = this.$parent.viewer;
      if (this.zoomOffset) {
        viewer.zoomTo(this.entity, generate(this.zoomOffset));
        return;
      }
      viewer.zoomTo(this.entity);
    },
    remove() {
      try {
        this?.viewer.entities.remove(this.entity);
      } catch (error) {}
    }
  }
};
